<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="text" id = 'username'> <button id = 'sign' onclick="signin()">input name and sign in</button>
    <input type="text" id="content" />
    <input type="button" value="发送" id="send" />
</body>
<script type="text/javascript">
    function signin(){
        console.log(2)
        var user = document.getElementById("username").value;
    /* 封装 WebSocket 实例化的方法  */
    var CreateWebSocket = (function () {
        return function (urlValue) {
            if(window.WebSocket) return new WebSocket(urlValue);
            if(window.MozWebSocket) return new MozWebSocket(urlValue);
            return false;
        }
    })();
    /* 实例化 WebSocket 连接对象, 地址为 ws 协议 */
    var webSocket = CreateWebSocket("ws://localhost:3000");
    /* 接收到服务端的消息时 */
    var count = 0; 
    webSocket.onopen = function () {
        var str = "welcome:" +  user;
        console.log(str);
        webSocket.send(JSON.stringify({name: user, msg: str}));
    };
    /* 接收到服务端的消息时 */
    webSocket.onmessage = function (msg) {
        console.log(msg);
        var data = JSON.parse(msg.data);
        console.log(data.name+ "说:" + data.msg);
    };
    /* 关闭时 */
    webSocket.onclose = function () {
        console.log("关闭连接");
    };
    /* 发送消息 */
    document.getElementById("send").onclick = function () {
        var str = document.getElementById("content").value;
        webSocket.send(JSON.stringify({name: user, msg: str}));
    }
}
</script>
</html>